package common

import (
	"hash/fnv"
	"path"
	"runtime"
	"strconv"
	"strings"
)

type Node struct {
	Addr string
	Id   int
}

type KeyValue struct {
	Key   string
	Value string
}

type Job struct {
	JobName         string
	TaskFilePathSlc []string
	MapNum          int
	ReduceNum       int
	TaskNumber      int
	MapFunc         func(string, string) []KeyValue
	ReduceFunc      func(string, []string) KeyValue
}

const (
	Map_Phase    = "Map"
	Reduce_Phase = "Reduce"
)

/**
  计算Key所对应的Reduce索引
*/
func ParseReduceHashIndex(key string, reduceNum int) int {
	keyHash := hash(key)
	return keyHash % reduceNum
}

func hash(s string) int {
	h := fnv.New32a()
	h.Write([]byte(s))
	return int(h.Sum32())
}

/**
  Map生成的文件名
*/
func GetMapFilePath(jobName string, mapNumber int, reduceNumber int) string {
	filePath := getProjectPath() + "txtFiles/"
	return filePath + "map_" + jobName + "_" + strconv.Itoa(mapNumber) + "_" + strconv.Itoa(reduceNumber) + ".txt"
}

/**
  Reduce生成的文件名
*/
func GetReduceFileName(jobName string, reduceNumber int) string {
	filePath := getProjectPath() + "txtFiles/"
	return filePath + "reduce_" + jobName + "_" + strconv.Itoa(reduceNumber) + ".txt"
}

/*
  获取项目路径 仅使用windows
*/
func getProjectPath() string {
	var projectPath string
	_, fileName, _, ok := runtime.Caller(0)
	if ok {
		projectPath = strings.Replace(path.Dir(fileName), "common", "", 1)
	}
	return projectPath
}
